<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
require_once '../../model/users.php';
require_once '../../model/email.php';
include_once("../../model/trade.php");
include_once("../../model/budget.php");
require_once '../../model/admindetails.php';
include_once '../../model/email.php';
require_once '../../model/message.php';
require_once "../../includes/classes/paging_htacess.php";
require_once '../../redirect.php';

## creating objects of required models
$userObj 		= new Model_Users();
$tradeObj = new Model_TRADE();
$budgetObj = new Model_Budget();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();
$msgObj = new Model_Message();


checkUserLogin();

if($_SESSION['user_type'] == '4')
{
	@header("location:".SITE_URL."/");
	exit;
}


$userId =$_SESSION['getbids_id'];
	
/*===========================================================================*/
	$userDetArray = $userObj->getUserDetailsByUserId($userId);
	$smarty->assign("userDetArray", $userDetArray);	
	
/*===========================================================================*/	
$jobsID = base64_decode($_GET['id2']);

// job detail	
	$jobdetArray = $userObj->getJobDetailsById($jobsID);
	// trade detail
	$gettradedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['trade_id']);	
	
	//jobtype detail
	$getjobtypedetail = $tradeObj->getTradeCategoryDetailsById($jobdetArray['jobtype_id']);


$cats = $jobdetArray['trade_category']. ' / '.$getjobtypedetail['trade_category'];


$smarty->assign('cats',$cats);



if(isset($_POST['accept']))
{
	extract($_POST);	
	$accept_primaryid = array_keys($_POST['accept']);

	//get user job view detail
	$getuserjobviewdetail = $userObj->getUserViewjobDetailsByID($accept_primaryid[0]);
	
	
	//tradesman detail 
	$TradesmanuserDetArray = $userObj->getUserDetailsByUserId($getuserjobviewdetail['userid']);

	$userjobviewArray = array();
	$userjobviewArray['status']	= 'Accept';
	$userObj->editUserViewJobValueById($userjobviewArray,$accept_primaryid[0]);	
	
	$userjobArray = array();
	$userjobArray['project_status']	= 'Accept';
	$userObj->editJobPostValueByJOBId($userjobArray,$jobsID);	
	

	// send email message to Tradesman accepted
	$email_message = $emailObj->getEmailById(13);
	$e_subject = $email_message['email_subject'];
	$message = $email_message['email_content']; 
	
	$subject = str_replace('[STATUS]', 'Accepted', $e_subject);
	$subject = str_replace('[SITENAME]', SITENAME, $subject);		 

	$message = str_replace('[TRADESMAN_NAME]', trim($TradesmanuserDetArray["first_name"])." ".trim($TradesmanuserDetArray["last_name"]) , $message);	
	$message = str_replace('[HOME_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
	$message = str_replace('[STATUS]','Accepted', $message);
	$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
	$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
	$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
	$message = str_replace('[SITENAME]', SITENAME, $message);
	
	
	
	$to= trim($TradesmanuserDetArray["email"]);
	$adminEmail = $adminObj->getAdminDetails();
	$from = $adminEmail;
	$fromname= SITENAME;
					 
	$emailTemplate = file_get_contents('../../emailtemplate.html');
	$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
	$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
	$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
	//echo $template_msg; exit;
	if(trim($to) != '')
	@send_mail($to, $template_msg, $subject, $from, $fromname); 
	
	//message add for inbox Tradesman
	$msgAddArray = array();
	$msgAddArray['from_id']   = '1'; 
	$msgAddArray['to_id'] 	  = $TradesmanuserDetArray["id"];
	$msgAddArray['ad_id']     = $jobsID;
	$msgAddArray['subject']   = $subject;
	$msgAddArray['message']   = $message;
	$msgAddArray['send_date'] = getCurDate();
	$msgAddArray['label'] 	  = 'inbox';
	$msgObj->addMessage($msgAddArray); # add record for inbox
	
	$msgAddArray['label'] 	  = 'outbox';
	$msgObj->addMessage($msgAddArray); # add record for outbox

	
	$getalluserjobview =$userObj->getallusersjobviewStatusOpen($jobsID);

	// send email message to All Tradesman rejected
	for($i=0;$i<count($getalluserjobview);$i++)
	{
		$userjobArray = array();
		$userjobArray['status']	= 'Decline';
		$userObj->editUserViewJobValueById($userjobArray,$getalluserjobview[$i]['id']);	

		//tradesman detail 
		$Tradesman_userDet = $userObj->getUserDetailsByUserId($getalluserjobview[$i]['userid']);
		
			$email_message = $emailObj->getEmailById(13);
			$e_subject = $email_message['email_subject'];
			$message = $email_message['email_content']; 
			
			$subject = str_replace('[STATUS]', 'Declined', $e_subject);
			$subject = str_replace('[SITENAME]', SITENAME, $subject);		 
		
			$message = str_replace('[TRADESMAN_NAME]', trim($Tradesman_userDet["first_name"])." ".trim($Tradesman_userDet["last_name"]) , $message);	
			$message = str_replace('[HOME_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
			$message = str_replace('[STATUS]','Declined', $message);
			$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
			$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
			$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
			$message = str_replace('[SITENAME]', SITENAME, $message);
			
			
			
			$to= trim($Tradesman_userDet["email"]);
			$adminEmail = $adminObj->getAdminDetails();
			$from = $adminEmail;
			$fromname= SITENAME;
							 
			$emailTemplate = file_get_contents('../../emailtemplate.html');
			$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
			$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
			$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
			//echo $template_msg; exit;
			if(trim($to) != '')
			@send_mail($to, $template_msg, $subject, $from, $fromname); 
			
			
			//message add for inbox Tradesman
			$msgAddArray = array();
			$msgAddArray['from_id']   = '1'; 
			$msgAddArray['to_id'] 	  = $Tradesman_userDet["id"];
			$msgAddArray['ad_id']     = $jobsID;
			$msgAddArray['subject']   = $subject;
			$msgAddArray['message']   = $message;
			$msgAddArray['send_date'] = getCurDate();
			$msgAddArray['label'] 	  = 'inbox';
			$msgObj->addMessage($msgAddArray); # add record for inbox
			
			$msgAddArray['label'] 	  = 'outbox';
			$msgObj->addMessage($msgAddArray); # add record for outbox
	
	}
	$_SESSION['msg'] = "<div class='success_msg'><span>You have accepted successfully!</span></div>";
	header('location:'.SITE_URL.'/jobs/'.$_GET['id1'].'/'.$_GET['id2'].'/myjobleads/');
	exit;	

	
}
if(isset($_POST['decline']))
{
	extract($_POST);
	$decline_primaryid = array_keys($_POST['decline']);
	
	//get user job view detail
	$getuserjobviewdetail = $userObj->getUserViewjobDetailsByID($decline_primaryid[0]);
	
	
	//tradesman detail 
	$TradesmanuserDetArray = $userObj->getUserDetailsByUserId($getuserjobviewdetail['userid']);

	$userjobArray = array();
	$userjobArray['status']	= 'Decline';
	$userObj->editUserViewJobValueById($userjobArray,$decline_primaryid[0]);	

	// send email message to Tradesman rejected
	$email_message = $emailObj->getEmailById(13);
	$e_subject = $email_message['email_subject'];
	$message = $email_message['email_content']; 
	
	$subject = str_replace('[STATUS]', 'Declined', $e_subject);
	$subject = str_replace('[SITENAME]', SITENAME, $subject);		 

	$message = str_replace('[TRADESMAN_NAME]', trim($TradesmanuserDetArray["first_name"])." ".trim($TradesmanuserDetArray["last_name"]) , $message);	
	$message = str_replace('[HOME_NAME]', trim($userDetArray["first_name"])." ".trim($userDetArray["last_name"]) , $message);
	$message = str_replace('[STATUS]','Declined', $message);
	$message = str_replace('[TRADE]', trim($gettradedetail["trade_category"]), $message);
	$message = str_replace('[JOBTYPE]', trim($getjobtypedetail["trade_category"]), $message); 
	$message = str_replace('[JOBDESC]', trim($jobdetArray["job_desc"]), $message); 
	$message = str_replace('[SITENAME]', SITENAME, $message);
	
	
	
	$to= trim($TradesmanuserDetArray["email"]);
	$adminEmail = $adminObj->getAdminDetails();
	$from = $adminEmail;
	$fromname= SITENAME;
					 
	$emailTemplate = file_get_contents('../../emailtemplate.html');
	$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
	$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
	$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
	
	if(trim($to) != '')
	@send_mail($to, $template_msg, $subject, $from, $fromname); 
	
		//message add for inbox Tradesman
			$msgAddArray = array();
			$msgAddArray['from_id']   = '1'; 
			$msgAddArray['to_id'] 	  = $TradesmanuserDetArray["id"];
			$msgAddArray['ad_id']     = $jobsID;
			$msgAddArray['subject']   = $subject;
			$msgAddArray['message']   = $message;
			$msgAddArray['send_date'] = getCurDate();
			$msgAddArray['label'] 	  = 'inbox';
			$msgObj->addMessage($msgAddArray); # add record for inbox
			
			$msgAddArray['label'] 	  = 'outbox';
			$msgObj->addMessage($msgAddArray); # add record for outbox
	
	$_SESSION['msg'] = "<div class='success_msg'><span>You have declined successfully!</span></div>";
	header('location:'.SITE_URL.'/jobs/'.$_GET['id1'].'/'.$_GET['id2'].'/myjobleads/');
	exit;	
}




## for pagination
	$page = $_GET['id1'];
	if(!isset($_GET['id1']))
	$page = 1;
	else
	$page = $page;
	
## limit per pag 
$tetsimonialPerPage =10;
$StartRow = $tetsimonialPerPage  * ($page-1);
## Getting all jobs from database according to user



$jobsArray  = $userObj->MYJOBLEADSAccordingToJOBId($jobsID,'','',false);



$totalCount        = count($jobsArray);
$smarty -> assign("recordsFound",$totalCount);

$result = $userObj->MYJOBLEADSAccordingToJOBId($jobsID,$tetsimonialPerPage,$StartRow,true);
$show = 1;
$total_pages = ceil($totalCount / $tetsimonialPerPage);
	if($total_pages > 1)
	$smarty -> assign("showpgnation","yes");
	$showing    = !isset($_GET["id1"]) ? 1 : $page;
	
	## it shoould be file name 
	if($_GET["id2"]!='')
		$firstlink  = $_GET["id2"]."/myjobleads/";
	else	
		$firstlink  ="/myjobleads/";
		
	$baselink   = $firstlink;
	if($total_pages!=0)
		$pagenation = pagination($total_pages, $show, $showing, $firstlink, $baselink, "", "jobs");
	$smarty -> assign("pagenation", $pagenation);
	$smarty -> assign("page", $page);
//	echo"<pre>";print_R($userrating);die();
	for($k=0;$k<count($result);$k++)
	{
		$userrating =$userObj->getUserRatingCount($result[$k]['userid']);
		if($userrating)
		{
			$user_ratingcnt = @round($userrating['ratingsum']/$userrating['cnt']);		
		
			$total_rating = $user_ratingcnt;
			$result[$k]['total_rating'] =$total_rating;
			//$smarty->assign('total_rating', $total_rating);
			if($total_rating < 5){
				$remaining_rating = 5 - $total_rating;
				$result[$k]['remaining_rating'] =$remaining_rating;
				//$smarty->assign('remaining_rating', $remaining_rating);
			} 
		}
		else
		{
			$result[$k]['total_rating'] =0;	
			$result[$k]['remaining_rating'] =5;
		}
	}	
	

	$smarty->assign("jobsArray", $result);


$getallTradeJobType = $tradeObj->getAllJobTypeWithActiveStatus();
$smarty->assign("getallTradeJobType", $getallTradeJobType);	

$getallBudget = $budgetObj->getAllBudgetWithActiveStatus();
$smarty->assign("getallBudget", $getallBudget);	


if($_SESSION['msg']){
		$smarty->assign("msg", $_SESSION['msg']);
		unset($_SESSION['msg']);
}


$smarty->assign('jobID',base64_encode($jobsID));
$active ="myaccount";
$smarty->assign('active',$active);
$subactive ="myjobleads";
$smarty->assign('subactive',$subactive);
$smarty->assign('mainmenu',"4");

$smarty->display(TEMPLATEDIR.'/modules/jobs/myjobleads.tpl');
unset($smarty);
?>
